////////////////////////////////////////////////////////////////////////////////
// checkstyle: Checks Java source code for adherence to a set of rules.
// Copyright (C) 2001-2012  Oliver Burn
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
////////////////////////////////////////////////////////////////////////////////
package ma.jeetconsulting.pocs.service;

import java.io.Closeable;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

import org.apache.maven.model.Model;
import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
import org.codehaus.plexus.util.xml.pull.XmlPullParserException;

/**
 * Contains utility methods.
 * 
 * @author Oliver Burn
 * @version 1.0
 */
public final class Utils {
	private static final Map<String, Pattern> CREATED_RES = new HashMap<>();

	private Utils() {
	}

	public static Pattern getPattern(String aPattern)
			throws PatternSyntaxException {
		return getPattern(aPattern, 0);
	}

	public static Pattern getPattern(String aPattern, int aCompileFlags)
			throws PatternSyntaxException {
		final String key = aPattern + ":flags-" + aCompileFlags;
		Pattern retVal = CREATED_RES.get(key);
		if (retVal == null) {
			retVal = Pattern.compile(aPattern, aCompileFlags);
			CREATED_RES.put(key, retVal);
		}
		return retVal;
	}

	

	public static void closeQuietly(Closeable aShutting) {
		if (null != aShutting) {
			try {
				aShutting.close();
			} catch (IOException e) {
				; // ignore
			}
		}
	}


	public static Model getPomObjectModel(String modulePath)
			throws FileNotFoundException, IOException, XmlPullParserException {
		final String POM_XML_PATH = "pom.xml"; 
		MavenXpp3Reader mavenreader = null;
		FileReader reader = null;
		try {
			mavenreader = new MavenXpp3Reader();
			reader = new FileReader(modulePath + File.separator
					+ POM_XML_PATH);
			return mavenreader.read(reader);
		} catch(FileNotFoundException e) {
			// Skip for the moment
		}
		
		return null;
	}
}
